<?php
/**
* Plugin Name: ArchivePress
* Plugin URI: http://code.google.com/p/archivepress/
* Description: Archiving blogs with blogs.
* Version: 1.1.0
* Author: University of London Computer Centre
* Author URI: http://code.google.com/p/archivepress/
* License: GPL2
*/
/**
 * @todo Delete it before the official release
 */
ini_set("display_errors","0");

/**
 * Constants declaration
 */
define('ARCHIVEPRESS','archivepress');
// Pre-2.6 compatibility
if ( ! defined( 'WP_PLUGIN_DIR' ) )
	define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
// ArchivePress plugin directory
define( 'WP_ARCHIVEPRESS_DIR', WP_PLUGIN_DIR . '/archivepress' );
// ArchivePress Prefix
define( 'WP_ARCHIVEPRESS_PREFIX', 'arpr_' );

/**
 * Plugin configuration & dependencies, Internationalization
 */
load_plugin_textdomain( ARCHIVEPRESS, WP_ARCHIVEPRESS_DIR );
require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.conf.php' );

/**
 * Global ArchivePress Class
 * @global ArchivePress $ArchivePress
 */
global $ArchivePress;

/**
 * Crontab functions
 *
 * Web and Unix crontab hooks and functions
 */
add_action('init', 'arpr_unix_or_web_fetch');
function arpr_unix_or_web_fetch() {
	require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.cron.php');
}

/**
 * Crontab functions
 *
 * WordPress crontab hook and function
 * @global ArchivePressLog $ArchivePressLog
 * @global ArchivePress $ArchivePress
 */
add_action('plugins_loaded', 'arpr_wp_fetch');
function arpr_wp_fetch() {
	global $ArchivePressLog;
	global $ArchivePress;

	// hourly scheduling (only if is wpcron)
	if( (time() - get_option(WP_ARCHIVEPRESS_PREFIX."cron") >= 3600) && (get_option(WP_ARCHIVEPRESS_PREFIX . "cronType") == ArchivePressOptions::CRON_WPCRON) ){
		// esecute script
		$ArchivePressLog->logIt(ArchivePressLog::LOG_DEBUG,__("Cron job started successfully.",ARCHIVEPRESS));

		// get active feeds
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);

		foreach($activeFeeds as $feed){
			// check if I have to fetch the feed
			if( (time() - strtotime($feed["last_update"])) >= (int)$feed["interval"] ) {
				if($feed["is_comment"] == "no"){
				    // fetch feed and its comment feeds
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
                    $ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeedComments($feed["id"], true)));
				}else{
					// do nothing
				}
			}
		}

		// update "last update"
		update_option(WP_ARCHIVEPRESS_PREFIX."cron",time());
	}
}

/**
 * Activate hook and function
 *
 * It works also for Updating
 */
function arpr_activate() {
	require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
	$ArchivePress->Activate();
}
register_activation_hook( __FILE__, 'arpr_activate' );

/**
 * Deactivate hook and function
 */
function arpr_deactivate() {
	require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
	$ArchivePress->Deactivate();
}
register_deactivation_hook( __FILE__, 'arpr_deactivate' );

/**
 * Remove hook and function
 */
function arpr_remove() {
	require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
	$ArchivePress->Remove();
}
register_uninstall_hook(__FILE__, 'arpr_remove');


/**
 * WordPress Admin Area
 *
 * Add ArchivePress Links to Favorite Menu
 */
function add_favorite_item($actions) {
    // for each admin page except for the ArchivePress ones
    if(!array_key_exists("page", $_GET)){
        // To show the ArchivePress Item as FIRST
        $tmpActions = array();
        $tmpActions[get_bloginfo( 'wpurl' ).'/wp-admin/admin.php?page=archivepress/pages/add-feed.php'] = array('Add New Feed', 'administrator');
        $actions = $tmpActions + $actions;
    } else if($_GET["page"] == "archivepress/pages/add-feed.php") { // add feed page
        // To show the ArchivePress Item as FIRST
        $tmpActions = array();
        $tmpActions[get_bloginfo( 'wpurl' ).'/wp-admin/admin.php?page=archivepress/pages/edit-posts.php'] = array('Show Feeds', 'administrator');
        $actions = $tmpActions + $actions;

    } else {
        // To show the ArchivePress Item as FIRST
        $tmpActions = array();
        $tmpActions[get_bloginfo( 'wpurl' ).'/wp-admin/admin.php?page=archivepress/pages/add-feed.php'] = array('Add New Feed', 'administrator');
        $actions = $tmpActions + $actions;
    }
    return $actions;
}
add_filter('favorite_actions', 'add_favorite_item');

/**
 * WordPress Admin Area
 *
 * Customize menu item positions freely
 */
add_filter('custom_menu_order','custom_menu_order_function');
    function custom_menu_order_function(){
    return true;
}

/**
 * WordPress Admin Area
 *
 * Add plugin menu and submenu links
 * @global array $menu
 * @global array $submenu
 * @global array $_registered_pages
 */
add_action('admin_menu', WP_ARCHIVEPRESS_PREFIX . 'add_pages');
function arpr_add_pages() {
    global $menu, $submenu, $_registered_pages;

    // Add a new menu separator
    $menu[2] = array('', 'read', 'separator0', '', 'wp-menu-separator');
    // New Top Level Menu
    add_menu_page('ArchivePress', 'ArchivePress', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', null, '../'.PLUGINDIR.'/archivepress/images/archivepress16.png', 3 );

    // Submenus
    // edit feeds
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Edit Post Feeds', 'Edit Post Feeds', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php');
    // edit comments
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Edit Comment Feeds', 'Edit Comment Feeds', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/edit-comments.php');
    // add new feed
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Add New', 'Add New Feed', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/add-feed.php');
    // authors
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Authors', 'Post Authors', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/authors.php');
    // logs
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Logs', 'Logs', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/logs.php');
    // settings
    add_submenu_page(WP_ARCHIVEPRESS_DIR . '/pages/edit-posts.php', 'Settings', 'Settings', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/settings.php');


    // ADD OTHER PAGES
    // these pages are INVISIBLE inside the menu
    // but visible from some ArchivePress Admin Areas

    // responder.php ($_GET actions)
    add_submenu_page('', 'responder', 'responder', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/responder.php');

    // metadata.php (feed metadata page)
    add_submenu_page('', 'metadata', 'metadata', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/metadata.php');

    // metadata-changelog.php (feed metadata changelog page)
    add_submenu_page('', 'metadatachangelog', 'metadatachangelog', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/metadata-changelog.php');

    // edit-post.php (edit feed page)
    add_submenu_page('', 'editpost', 'editpost', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/edit-post.php');

    // edit-comment.php (edit comment feed page)
    add_submenu_page('', 'editcomment', 'editcomment', 'administrator', WP_ARCHIVEPRESS_DIR . '/pages/edit-comment.php');

}

/**
 * WordPress Admin Area
 *
 * Admin pages stylesheet
 */
function archivepress_admin_style() {
    echo "<link rel='stylesheet' href='".WP_PLUGIN_URL."/archivepress/css/wp-admin.css' type='text/css' media='all' />";
}
add_action('admin_head', 'archivepress_admin_style');

/**
 * WordPress Admin Area
 *
 * Admin actions
 */
function archivepress_admin_actions() {
    if(count($_GET) > 0){
        if(array_key_exists(WP_ARCHIVEPRESS_PREFIX . "action", $_GET)) {
            require_once(WP_PLUGIN_DIR."/archivepress/pages/responder.php");
        }
    }
    if(count($_POST) > 0){
        if(array_key_exists(WP_ARCHIVEPRESS_PREFIX . "action", $_POST)) {

            require_once(WP_PLUGIN_DIR."/archivepress/pages/responder.php");
        }
    }
}
add_action('admin_head', 'archivepress_admin_actions');

/**
 * WordPress Admin Area
 *
 * Plugin list "Settings" link
 */
function arpr_plugin_settings($links, $file){
    static $this_plugin;

    if( !$this_plugin ) $this_plugin = plugin_basename(__FILE__);

    if( $file == $this_plugin ){
        $settings_link = '<a href="admin.php?page=archivepress/pages/settings.php">' . __('Settings', ARCHIVEPRESS) . '</a>';
        $links = array_merge( array($settings_link), $links); // before other links
    }
    return $links;
}
add_filter( 'plugin_action_links', WP_ARCHIVEPRESS_PREFIX . 'plugin_settings', 10, 2 );

/**
 * WordPress Admin Area
 *
 * Create the WP dashboard Widget "ArchivePress Right Now"
 * @global ArchivePress $ArchivePress
 */
function archivepress_dashboard_widget_function() {
    // moved to a proper page
    require('widgets/right-now.php');
}

/**
 * WordPress Admin Area
 *
 * Create the WP dashboard Widget "ArchivePress Log"
 * @global ArchivePress $ArchivePress
 */
function archivepress_dashboard_logs_widget_function() {
    // moved to a proper page
    require('widgets/logs.php');
}

/**
 * WordPress Admin Area
 *
 * Dashboard Widgets hooks
 */
function archivepress_add_dashboard_widgets() {
	wp_add_dashboard_widget('archivepress_dashboard_widget', 'ArchivePress Right Now', 'archivepress_dashboard_widget_function');
	wp_add_dashboard_widget('archivepress_dashboard_log_widget', 'ArchivePress Logs', 'archivepress_dashboard_logs_widget_function');
}

/**
 * WordPress Admin Area
 *
 * Hook into the 'wp_dashboard_setup' action to register our other functions
 */
add_action('wp_dashboard_setup', 'archivepress_add_dashboard_widgets' );

/**
 * WordPress Admin Area
 *
 * Add Dashboard Widgets Head Stuff (css, javascript and redirection after saving configuration)
 */
function archivepress_custom_style_script() {
    // elaborate form post (Log Widget Settings)
    if(isset($_POST)){
        if(array_key_exists("archivepress_dashboard_log_widget_items",$_POST)){
            // security
            check_admin_referer(ARCHIVEPRESS . "-update-options_log-options");

            update_option(WP_ARCHIVEPRESS_PREFIX."log_widget_show",attribute_escape($_POST["archivepress_dashboard_log_widget_type"]));
            update_option(WP_ARCHIVEPRESS_PREFIX."log_widget_items",attribute_escape($_POST["archivepress_dashboard_log_widget_items"]));
            wp_redirect(get_bloginfo( 'wpurl' ).'/wp-admin/index.php');
        }
    }

    // add css and js declaration inside the <head>
    echo "<link rel='stylesheet' href='".WP_PLUGIN_URL."/archivepress/css/widgets.css' type='text/css' media='all' />";

	// widget js: if js is not enabled the widget will work anyway, but the links will be a bit more "ugly"
	$edit = "";
	if(isset($_GET["edit"])){
		$edit = attribute_escape($_GET["edit"]);
	}
	if($edit == "archivepress_dashboard_log_widget"){
		echo '<script type="text/javascript">
		         //<![CDATA[
				jQuery(document).ready(function($) {
					var html = $("#archivepress_dashboard_log_widget h3:first span:first").html();
					html = html + <span class="postbox-title-action"><a href="'.get_bloginfo( 'wpurl' ).'/wp-admin/index.php" class="open-box">'.__("Cancel",ARCHIVEPRESS).'</a></span>;
					$("#archivepress_dashboard_log_widget h3:first span:first").html(html);
				});
				//]]>
			 </script>';
	}else{
		echo "<script type='text/javascript'>
		         //<![CDATA[
				jQuery(document).ready(function($) {
					var html = $('#archivepress_dashboard_log_widget h3:first span:first').html();
					html = html + \"<span class='postbox-title-action' ><a href='?edit=archivepress_dashboard_log_widget#archivepress_dashboard_log_widget' class='edit-box open-box'>".__('Configure',ARCHIVEPRESS)."</a></span>\";
					$('#archivepress_dashboard_log_widget h3:first span:first').html(html);
				});
				//]]>
			 </script>";
	}
}
add_action('admin_head', 'archivepress_custom_style_script');

/**
 * ArchivePress WordPress Template tags
 *
 * Get special page links
 */
function arpr_getpage($page) {
	return get_page_link((int)get_option(WP_ARCHIVEPRESS_PREFIX.$page));
}

/**
 * ArchivePress WordPress Template tags
 *
 * Original post link
 */
function arpr_get_ori_link($post_id){
	return get_post_meta($post_id, WP_ARCHIVEPRESS_PREFIX."original_url",true);
}

/**
 * ArchivePress WordPress Template tags
 *
 * Post fetch date
 */
function arpr_get_fetch_date($post_id){
	return get_post_meta($post_id, WP_ARCHIVEPRESS_PREFIX."fetch_date",true);
}

/**
 * ArchivePress WordPress Template tags
 *
 * Original blog link
 * @global ArchivePress $ArchivePress
 */
function arpr_get_blog_link($cat_id){
	// globals
	global $ArchivePress;

	return $ArchivePress->get_blog_link((int)$cat_id);
}
?>